/*(function($, Vue) {*/
var vmdata = {
	isAddOrg : true,
    slideBar: [], //侧边栏
    active: '', //当前菜单resCode
    orgText : '',//选中的组织名称
    content: { //表格数据
        org_manage: { //组织管理
            parmObj: { //新建组织
                name: '',
                loginId: '',
                password: '',
                ouId: ''
            },
            thead: [
                { title: '组织名称', key: 'name', sortable: true },
                { title: '创建时间', key: 'registeTime', sortable: true },
                {
                    title: '部门',
                    key: 'departments',
                    render: function (h, params) {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'text',
                                    size: 'small'
                                },
                                on: {
                                    click: function () {
                                        vmdata.orgText = params.row.name;
                                        vmdata.active = 'department_manage';
                                        departmentPageObj.addParamObj.outId = params.row.ouId;
                                        getDeptList();
                                    }
                                }
                            }, '查看')
                        ]);
                    }
                },
                {
                    title: '操作',
                    key: 'oprations',
                    render: function (h, params) {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'text',
                                    size: 'small'
                                },
                                on: {
                                    click: function () {
                                    	vmdata.modal.title = '编辑组织';
                                    	vmdata.modal.type = 'editorOrg';
                                        vmdata.modal.showOrg = true;

                                        vmdata.content.org_manage.parmObj.name = params.row.name;
                                        vmdata.content.org_manage.parmObj.loginId = -1;
                                        vmdata.content.org_manage.parmObj.password = -1;
                                        vmdata.content.org_manage.parmObj.ouId = params.row.ouId;
                                    }
                                }
                            }, '编辑'),
                            h('Button', {
                                props: {
                                    type: 'text',
                                    size: 'small'
                                },
                                on: {
                                    click: function () {
                                        vmdata.confirmModel = {
                                            show : true,
                                            title: '删除组织',//标题
                                            type: 'orgDelete',//类型
                                            text: '确认删除' + params.row.name + '？',//内容
                                            param: params//对象，传参
                                        };
                                    }
                                }
                            }, '删除')
                        ]);
                    }
                }
            ],
            tbody: []
        },
        user_manage: { //用户管理
            thead: [
                { title: '姓名', key: 'name', sortable: true },
                { title: '账号', key: 'loginId', sortable: true },
                { title: '所属组织', key: 'orgName', sortable: true },
                { title: '所属部门', key: 'deptName', sortable: true },
                { title: '角色', key: 'roleName', sortable: true },
                { title: '状态', key: 'status', sortable: true },
                { title: '创建时间', key: 'registerTime', sortable: true },
                {
                    title: '操作',
                    key: 'oprations',
                    render: function (h, params) {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'text',
                                    size: 'small'
                                },
                                on: {
                                    click: function () {
                                        var value = params.row;
                                        userAddObj.addParamObj = {
                                            userId : value.userId,
                                            loginId : value.loginId,
                                            name : value.name,
                                            password : '',
                                            confirmPassword : '',
                                            idNumber : value.idNumber,
                                            mobilephone : value.mobilephone,
                                            email : value.email,
                                            roleId : value.casssoRoleVO.roleId,
                                            ouId : value.casssoOrganizationUnitVO.ouId,
                                            deptId : value.casssoDeptVO.deptId
                                        };

                                        userAddObj.idNumber = value.idNumber;
                                        userAddObj.mobilephone = value.mobilephone;
                                        userAddObj.email = value.email;
                                        userAddObj.orgId = value.casssoOrganizationUnitVO.ouId;

                                        initAddUserData(true);

                                        userAddObj.deptValue = value.deptIds;
                                        getDeptList(value.ouId);
                                    	vmdata.modal.title = '编辑用户';
                                        vmdata.modal.showUser = true;
                                    }
                                }
                            }, '编辑'),
                            h('Button', {
                                props: {
                                    type: 'text',
                                    size: 'small'
                                },
                                on: {
                                    click: function () {
                                        vmdata.confirmModel = {
                                            show : true,
                                            title: '删除用户',//标题
                                            type: 'userDelete',//类型
                                            text: '确认删除' + params.row.name + '？',//内容
                                            param: params//对象，传参
                                        };
                                    }
                                }
                            }, '删除')
                        ]);
                    }
                }
            ],
            tbody: []
        },
        access_manage: { //接入管理
            thead: [
                { title: '系统名称', key: 'sysName', sortable: true },
                { title: '组织名称', key: 'name', sortable: true },
                { title: '跳转Url', key: 'url', sortable: true },
                { title: '创建时间', key: 'createTime', sortable: true },
                {
                    title: '操作',
                    key: 'oprations',
                    render: function (h, params) {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'text',
                                    size: 'small'
                                },
                                on: {
                                    click: function () {
                                        var value = params.row;
                                        accessAddObj.addParamObj = {
									        sysName : value.sysName,
									        url : value.url,
									        ouId : value.ouId,
									        sysId : value.sysId
										}
                                        
                                        initAddAccessData();
                                        
                                        accessAddObj.addTitle = '编辑系统';
										
                						vmdata.modal.showAccess = true;
                                    }
                                }
                            }, '编辑'),
                            h('Button', {
                                props: {
                                    type: 'text',
                                    size: 'small'
                                },
                                on: {
                                    click: function () {
                                        vmdata.confirmModel = {
                                            show : true,
                                            title: '删除接入系统',//标题
                                            type: 'accessDelete',//类型
                                            text: '确认删除' + params.row.sysName + '？',//内容
                                            param: params//对象，传参
                                        };
                                    }
                                }
                            }, '删除')
                        ]);
                    }
                }
            ],
            tbody: []
        },
        role_manage: { //角色管理
            thead: [
                { title: '角色名称', key: 'roleName', sortable: true },
                { title: '创建时间', key: 'createTime', sortable: true }
            ],
            tbody: []
        },
        personal_manage: { //个人中心
            name: '',
            loginId: '',
            password : '',
            confirmPassword : '',
            idNumber : '',
            email: '',
            mobilephone: ''
        }
    },
    modal: {
    	title : '',
    	type : '',
        showOrg: false,
        showUser : false,//显示新增用户弹出框
        showAccess : false//显示新增介入系统弹出框
    },
    confirmModel: {
        show : false,
        title: '',//标题
        type: '',//类型
        text: '',//内容
        param: null//对象，传参
    },
    search: {
        type: '',
        value: ''
    },
    userStatus: { //用户状态映射关系
        '-1': '已删除',
        0: '待审核',
        1: '待激活',
        2: '已激活',
        3: '已停用'
    },
    page: { //分页器
        current: '',
        total: '',
        pageSize: ''
    },
    normalAlert : '',
    successAlert : '',
    warningAlert : '',
    errorAlert : '',
    normalAlertTimer : null,
    successAlertTimer : null,
    warningAlertTimer : null,
    errorAlertTimer : null,

    showEditPsw : '隐藏密码',
    
    isEditor : false//用户是否修改了个人中心资料
};

var vm = new Vue({
    el: '#app',
    data: vmdata,
    watch: {
        normalAlert : function () {
            var _this = this;
            clearTimeout(this.normalAlertTimer);

            if (this.normalAlert) {
                this.normalAlertTimer = setTimeout(function () {
                    _this.normalAlert = '';
                }, 10000);
            }

        },
        successAlert : function () {
            var _this = this;
            clearTimeout(this.successAlertTimer);

            if (this.successAlert) {
                this.successAlertTimer = setTimeout(function () {
                    _this.successAlert = '';
                }, 10000);
            }
        },
        warningAlert : function () {
            var _this = this;
            clearTimeout(this.warningAlertTimer);

            if (this.warningAlert) {
                this.warningAlertTimer = setTimeout(function () {
                    _this.warningAlert = '';
                }, 10000);
            }
        },
        errorAlert : function () {
            var _this = this;
            clearTimeout(this.errorAlertTimer);
            
            if (this.errorAlert) {
                this.errorAlertTimer = setTimeout(function () {
                    _this.errorAlert = '';
                }, 10000);
            }
        }
    },
    methods: {
        select: function(resCode) { //切换侧边栏
            var _this = this;
            
            vmdata.active = resCode;
            
            vmdata.search.value = '';

            switch (resCode) {
                case 'org_manage': //组织列表
                    getOrgList();
                break;
                case 'user_manage': //用户管理
                    getUserList.call(_this, 1); //默认第一页
                break;
                case 'access_manage': //接入管理
                    getAccessList.call(_this);
                break;
                case 'role_manage': //角色管理
                    getRoleList.call(_this);
                break;
                case 'personal_manage': //个人中心
                    getPersonalData(_this);
                break;

                case 'monitor': //实时监控
                    getMonitorList();
                break;

                default:
                    return;
            }
        },
        changePersonal : function () {
        	this.isEditor = true;
        },
        confirmPswChangePersonal : function () {
        	this.isEditor = true;
        	if (this.content.personal_manage.confirmPassword !== this.content.personal_manage.password) {
        		vmdata.warningAlert = '两次输入密码不一致，请重新输入！';
        	} else {
        		vmdata.warningAlert = '';
        	};
        },
        savePersonal : function () {
            var _this = this;

            var saveUrl = '/cas/console/user/personalEdit.ajax';

            var saveCallback = function (rs) {
                if (rs.isSuccess) {
                	this.isEditor = false;
                	
                    vmdata.successAlert = '修改成功！';
                    _this.select('personal_manage');
                } else {
                    vmdata.errorAlert = rs.errMsg;
                }
            };

            if (this.showEditPsw !== '修改密码' || !this.content.personal_manage.password) {
                delete this.content.personal_manage.password;
            } else {
            	if (this.content.personal_manage.confirmPassword !== this.content.personal_manage.password) {
	        		vmdata.warningAlert = '两次输入密码不一致，请重新输入！';
	        		return
	        	} else {
	        		vmdata.warningAlert = '';
	        	};
            }

            var param = this.content.personal_manage;

            $.ajax({
                type: "POST",
                url: saveUrl,
                async: true,
                contentType: "application/json",
                dataType: "json",
                data: JSON.stringify(param),
                success: saveCallback
            });
        },
        showModal: function(type, title) { //展示浮层
            if (type === 'addOrg') {
                vmdata.modal.title = '新增组织';
            	vmdata.modal.type = 'addOrg';
                vmdata.modal.showOrg = true;

                vmdata.content.org_manage.parmObj.name = '';
                vmdata.content.org_manage.parmObj.loginId = '';
                vmdata.content.org_manage.parmObj.password = '';
                vmdata.content.org_manage.parmObj.ouId = '';
            } else if (type === 'addUser') {
                initAddUserData();
                vmdata.modal.title = '新增用户';
                vmdata.modal.showUser = true;
            } else if (type === 'addAccess') {
                initAddAccessData();
                
                accessAddObj.addParamObj = {
			        sysName : '',
			        url : '',
			        ouId : '',
			        sysId : ''
				}
                                        
                accessAddObj.addTitle = '新增系统';

                vmdata.modal.showAccess = true;
            }
        },
        userPage: function(current) { //用户列表翻页
            getUserList(current);
        },
        logout: function() {
            location.href = '/cas/logout';
        },
        searchImf: function (type) {
            var _this = this;

            if (type === 'searchOrg') {
                _this.search.type = 'org';
                var searchValue = _this.search.value;
                var searchUrl = '/cas/console/org/fuzzyQuery.ajax';

                var searchCallback = function (rs) {
                    var data = rs.data;

                    if (rs.isSuccess) {
                        vmdata.content.org_manage.tbody = handleOrgData(data);
                    } else {
                        _this.$Message.info(rs.errMsg);
                    }
                };

                if (searchValue) {
                    $.get(searchUrl,{name : searchValue},searchCallback, "json");
                } else {
                    getOrgList();
                }
            } else if (type === 'searchUser') {
                _this.search.type = 'user';
                var searchValue = _this.search.value;
                var searchUrl = '/cas/console/user/fuzzyQuery.ajax';

                var searchCallback = function (rs) {
                    var data = rs.data;

                    if (rs.isSuccess) {
                        data = handleUserData(data);

                        vmdata.content.user_manage.tbody = [];
                        vmdata.content.user_manage.tbody = data.userList;
                    } else {
                        _this.$Message.info(rs.errMsg);
                    }
                };

                if (searchValue) {
                    $.get(searchUrl,{key : searchValue},searchCallback, "json");
                } else {
                    getUserList.call(_this, 1);
                }
            } else if (type === 'searchAccess') {
                _this.search.type = 'access';
                var searchValue = _this.search.value;
                var searchUrl = '/cas/console/sys/fuzzyQuery.ajax';

                var searchCallback = function (rs) {
                    if (rs.isSuccess) {
                        var data = rs.data;
                        data.forEach(function(obj) {
                            obj.createTime = formatDate(obj.createTime);
                            obj.name = obj.casssoOrganizationUnitVO.name;
                            return obj;
                        });

                        vmdata.content.access_manage.tbody = [];
                        vmdata.content.access_manage.tbody = data;
                    } else {
                        _this.$Message.info(rs.errMsg);
                    }
                };

                if (searchValue) {
                    $.get(searchUrl,{key : searchValue},searchCallback, "json");
                } else {
                    getAccessList.call(_this, 1);
                }
            }
        },
        confirmOk: function (type,params) {
            var _this = this;

            switch (type) {
                case 'orgDelete':
                    var ouId = params.row.ouId;

                    var deleteUrl = '/cas/console/org/delete.ajax';
                    var deleteCallback = function (rs) {
                        if (rs.isSuccess) {
                            vmdata.successAlert = '删除成功！';
                            getOrgList();
                        } else {
                            vmdata.errorAlert = rs.errMsg;
                        }
                    };
                    $.get(deleteUrl,{ouId : ouId},deleteCallback,'json');
                break;

                case 'userDelete':
                    var userid = params.row.userId;

                    var deleteUrl = '/cas/console/user/delete.ajax';
                    var deleteCallback = function (rs) {
                        if (rs.isSuccess) {
                            vmdata.successAlert = '删除成功！';
                            getUserList.call(_this, 1);
                        } else {
                            vmdata.errorAlert = rs.errMsg;
                        }
                    };
                    $.post(deleteUrl,{userId : userid},deleteCallback,'json');
                break;

                case 'monitorOffLine':
                    var tgt = params.row.tgt;

                    var enofflineUrl = '/cas/console/monitor/enoffline.ajax';

                    var enofflineCallback = function (rs) {
                        if (rs.isSuccess) {
                            vmdata.successAlert = '操作成功！';
                            getMonitorList();
                        } else {
                            vmdata.errorAlert = rs.errMsg;
                        }
                    };

                    $.post(enofflineUrl,{tgt : tgt}, enofflineCallback);
                break;
                
                case 'accessDelete':
                	var sysId = params.row.sysId;
                	
                	var deleteUrl = '/cas/console/sys/delete.ajax';

                    var deleteCallback = function (rs) {
                        if (rs.isSuccess) {
                            vmdata.successAlert = '操作成功！';
                            getAccessList();
                        } else {
                            vmdata.errorAlert = rs.errMsg;
                        }
                    };

                    $.post(deleteUrl,{sysId : sysId}, deleteCallback);
                break;
            }
        },
        confirmCancel: function () {
            
        }
    },
    mounted : function () {
    	getPersonalData(this);
    }
});

//初始化侧边栏
$.get('/cas/console/res/queryMenu.ajax').done(function(rs) {
    if (rs.isSuccess) {
        vmdata.slideBar = rs.data;
        setTimeout(function() {
            $('.ivu-menu li').first().click();
        }, 0);
    }
});

function handleOrgData(data) {
    data.forEach(function(obj) {
        obj.registeTime = formatDate(obj.registeTime);
        return obj;
    });
    
    return data;
}

//个人中心
function getPersonalData(_this) {
	$.get('/cas/console/user/query.ajax').done(function(rs) {
	    if (rs.isSuccess) {
	        vmdata.content.personal_manage = rs.data;
	        vmdata.content.personal_manage.password = '';
            vmdata.content.personal_manage.confirmPassword = '';
	        vmdata.showEditPsw = '隐藏密码';
	    } else {
	        _this.$Message.info(rs.errMsg);
	    }
	    
	    _this.isEditor = false;
	});
}

//组织管理
function getOrgList(getList) {
    var _this = this;
    $.get('/cas/console/org/queryAll.ajax').done(function(rs) {
        if (rs.isSuccess) {
            var data = rs.data;

            if (getList) {
                userAddObj.orgData = [];
                accessAddObj.orgData = [];

                if (data && typeof data !== 'string') {
                    data.forEach(function (obj) {
                        var value = obj.ouId;
                        var label = obj.name;

                        var o = {
                            value : value,
                            label : label
                        };

                        userAddObj.orgData.push(o);
                        accessAddObj.orgData.push(o);
                    });
                }
            } else {
            	if (getRoleJuri() !== 'super_admin') {
            		vmdata.isAddOrg = false;
            	};
            	
                vmdata.content.org_manage.tbody = handleOrgData(data);
            }
        } else {
            vmdata.errorAlert = rs.errMsg;
        }
    });
}

function handleUserData(data) {
    vmdata.page = {
        current: data.pageIndex,
        total: data.total,
        pageSize: data.pageSize
    };

    if (data.userList && typeof data.userList !== 'string' && data.userList.length > 0) {
        data.userList.forEach(function(obj){
            obj.orgName = obj.casssoOrganizationUnitVO?obj.casssoOrganizationUnitVO.name:'';
            obj.deptName = obj.casssoDeptVO?obj.casssoDeptVO.name:'';
            obj.status = vmdata.userStatus[obj.status];
            obj.roleName = obj.casssoRoleVO?obj.casssoRoleVO.roleName:'';
            obj.registerTime = obj.registerTime?formatDate(obj.registerTime):'';
            return obj;
        });
    } else {
        data.userList = [];
    }

    return data
}

//用户管理
function getUserList(pageIndex) {
    var _this = this;
    $.get('/cas/console/user/pageQuery.ajax?pageIndex=' + pageIndex).done(function(rs) {
        if (rs.isSuccess) {
            //设置分页器
            var data = rs.data;

            //解析JSON
            data = handleUserData(data);

            vmdata.content.user_manage.tbody = [];
            vmdata.content.user_manage.tbody = data.userList;
        } else {
            _this.$Message.info(rs.errMsg);
        }
    });
}

//接入管理
function getAccessList() {
    var _this = this;
    $.get('/cas/console/sys/pageQuery.ajax').done(function(rs) {
        if (rs.isSuccess) {
            var data = rs.data;
            data.forEach(function(obj) {
                obj.createTime = formatDate(obj.createTime);
                obj.name = obj.casssoOrganizationUnitVO.name;
                return obj;
            });
            vmdata.content.access_manage.tbody = data;
        } else {
            _this.$Message.info(rs.errMsg);
        }
    });
}

var getRoleJuri = function () {
    var roleCode = '';
    $.ajax({
        type: "GET",
        url: '/cas/console/role/queryRole.ajax',
        data: null,
        success: function (rs) {
            if (rs.isSuccess) {
                var data = rs.data;
                roleCode = data.roleCode;
            } else {
                _this.$Message.info(rs.errMsg);
            }
        },
        async: false,
        contentType: "application/json",
        dataType: "json"
    });

    return roleCode;
};

//角色管理
function getRoleList(getList) {
    var _this = this;

    var url = '/cas/console/role/query.ajax';
    var roleCode = '';

    if (getList) {
        roleCode = getRoleJuri();
    }

    $.get(url).done(function(rs) {
        if (rs.isSuccess) {
            var data = rs.data;

            if (getList) {
                userAddObj.roleData = [];

                if (data && typeof data !== 'string') {
                    data.forEach(function (obj) {
                        var handle = function () {
                            var value = obj.roleId;
                            var label = obj.roleName;

                            userAddObj.roleData.push({
                                value : value,
                                label : label
                            });
                        };
                        if (roleCode === 'super_admin' || !roleCode) {
                            handle();
                        } else {
                            if (obj.roleCode !== 'super_admin') {
                                handle();
                            }
                        }
                    });
                }
            } else {
                data.forEach(function(obj) {
                    obj.createTime = formatDate(obj.createTime);
                    return obj;
                });
                vmdata.content.role_manage.tbody = data;
            }
        } else {
            _this.$Message.info(rs.errMsg);
        }
    });
}

//时间戳转日期
Vue.filter('formatDate', function (timestamp) {
    var now = new Date(timestamp),
        year = now.getFullYear(),
        month = format(now.getMonth() + 1),
        date = format(now.getDate());

    function format(p) {
        p < 10 ? p = '0' + p : null;
        return p;
    }
    return year + '-' + month + '-' + date;
});

function formatDate(timestamp) {
    var now = new Date(timestamp),
        year = now.getFullYear(),
        month = format(now.getMonth() + 1),
        date = format(now.getDate());

    function format(p) {
        p < 10 ? p = '0' + p : null;
        return p;
    }
    return year + '-' + month + '-' + date;
};

//传JSON串
function postJson(url, parm, options) {
    return $.ajax($.extend({
        url: url,
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(parm)
    }, options));
}

/*}(jQuery, Vue));*/
